var express = require('express');
var mongodb_ = require('./mongoose.js');
var mongo_ = new mongodb_();
var router = express.Router();
var async = require('async');
var userinfoSchema = {
    openid: String,
    nickname: String,
    date: Date,
    share: {
        type: Number,
        default: 0
    }
}
router.post('/submit', function(req, res, next) {
    console.log('getawayfromearth');
    var openid = req.body.openid;
    var nickname = req.body.nickname;

    var userinfo = {};
    userinfo.openid = openid;
    userinfo.nickname = nickname;
    userinfo.date = new Date();
    var userinfoschema = mongo_.getSchema(userinfoSchema);
    var userinfoModel = mongo_.getModel('getawayfromearth_userinfo', userinfoschema, 'getawayfromearth_userinfo');
    async.waterfall([
        function(cb) {
            userinfoModel.find({ openid: openid }, function(err, result) {
                if (err) { res.send(500, { message: err }) }
                if (result.length > 0) {
                    //判断日期是不是新的一天

                    if (userinfo.date.getTime() - result[0].date.getTime() > 60 * 60 * 24) {
                        console.log(1)
                        userinfo.share = 1;
                    } else {
                        console.log(2)
                        userinfo.share = result[0].share + 1;
                    }
                    cb(null, "update", userinfo);
                } else {
                    userinfo.share = 1;
                    cb(null, "save", userinfo);
                }
            });
        },
        function(op, userinfo, cb) {
            if (op == "save") {
                var userinfoEntity = new userinfoModel(userinfo);
                userinfoEntity.save(function(err) {
                    if (err) { cb(new Error(err)) } else {
                        cb(null, userinfo);
                    }
                });
            }
            if (op == "update") {
                userinfoModel.update({ openid: openid }, userinfo, function(err) {
                    if (err) { cb(new Error(err)) } else {
                        cb(null, userinfo);
                    }
                });
            }
        }
    ], function(err, result) {
        if (err) {
            res.send(500, { message: err })
        } else {
            res.send(200, { message: result.share });
        }
    });
});

router.get('/getUsers', function(req, res, next) {
    var openid = req.query.openid;
    var userinfoschema = mongo_.getSchema(userinfoSchema);
    var userinfoModel = mongo_.getModel('getawayfromearth_userinfo', userinfoschema, 'getawayfromearth_userinfo');
    userinfoModel.find({ openid: openid }, function(err, result) {
        if (err) { res.send(500, { message: err }) }
        if (result.length > 0) {
            res.send(result);
            return;
        }
        res.send(500, { message: "没有获取到任何参与活动者的电话信息" })
    });
});

module.exports = router;
